#include <memory>
#include <iostream>
#include <unistd.h>
//#include<sys/poll.h>
#include<sys/epoll.h>
#include "Socket.hpp"
#include "Log.hpp"

using namespace SocketModule;
using namespace LogModule;

class EpollServer
{
    const static int defaultfd = -1;
    //const static int size = sizeof(fd_set) * 8; // 辅助数组的大小
    const static int size = 64;
    
public:
    EpollServer(int port) : _listensock(std::make_unique<TcpSocket>()), _isrunning(false), _epfd(defaultfd)
    {
          //1、创建listensock
          _listensock->BuildTcpClientSocketMethod();
          //2、创建epoll模型
          _epfd = epoll_create(256);
          if(_epfd < 0)
          {
             LOG(LogLevel::FATAL) << "epoll create error !";
             exit(EPOLL_CREATE_ERROR);
          }
           LOG(LogLevel::INFO) << "epoll create success !";

           //3、将listensock设置进内核中
           struct epoll_event ev;
           ev.events = EPOLLIN;
           ev.data.fd = _listensock->FD();
           int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listensock->FD(), &ev);
           if(n < 0)
           {
                LOG(LogLevel::FATAL) << "add listensock failed !";
                exit(EPOLL_CREATE_ERROR);
           }

        // // for (int i = 0; i < size; i++)
        // //     _fd_arry[i] = defaultfd;
        // // _fd_arry[0] = _listensock->Fd();
        // for(int i = 0; i < size; i++)
        // {
        //     _fds[i].fd = defaultfd;
        //     _fds[i].events = 0;
        //     _fds[i].revents = 0;
        // }
        // _fds[0].fd = _listensock->Fd();
        // _fds[0].events = POLLIN;

    }

    void Start()
    {
        int timeout = -1;
        _isrunning = true;
        while (true)
        {
            PrintFd();
            int n = epoll_wait(_epfd, _revs, size, timeout); 
            //int n = poll(_fds, size, timeout);
            switch (n)
            {
            case -1:
                LOG(LogLevel::ERROR) << "epoll error !";
                break;
            case 0:
                LOG(LogLevel::INFO) << "time out...";
                break;
            default:
                // 有事件就绪：可能是新连接到来或者是普通fd上的读事件就绪
                LOG(LogLevel::INFO) << "有事件就绪..., n = " << n;
                Dispatcher(n); // 处理就绪事件
                break;
            }
        }

        _isrunning = false;
    }

    // 事件派发器
    void Dispatcher(int rnum)
    {
        LOG(LogLevel::DEBUG) << "envet ready ..."; //默认LT触发
       for(int i = 0; i < rnum; i++)
       {
          //epoll也要循环处理就绪事件-- 因为有可能有多个fd就绪！
          int sockfd = _revs[i].data.fd;
          uint32_t revent = _revs[i].events;
          if(revent & EPOLLIN)
          {
                //读事件就绪
                //1.新连接到来
                if(sockfd == _listensock->FD())
                {
                    Accpter();
                }
                else
                {
                    //2. 普通读事件
                    Recever(sockfd);
                }
          }
          if(revent & EPOLLOUT)
          {
              //写事件就绪 todo
          }
       }
    }

    // 连接管理器
    void Accpter()
    {
        InetAddr client;
        int connectfd = _listensock->Accept(&client); // 新连接到来 --- 至少有一个连接到来 --- accept一次 --- 绝对不会阻塞
        if (connectfd >= 0)
        {
            LOG(LogLevel::INFO) << "get a new link, sockfd: " << connectfd << ", client is: " << client.StringAddr();
           //将新的connectfd添加到内核
           struct epoll_event ev;
           ev.events = EPOLLIN;
           ev.data.fd = connectfd;
           int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, connectfd, &ev);
           if(n < 0)
           {
              LOG(LogLevel::WARING) << "add connectfd failed !";
           }
           else
           {
              LOG(LogLevel::INFO) << "epoll_ctl add connectfd success:" << connectfd;
           }
        }
    }

    // IO处理器
    void Recever(int sockfd)
    {
        char buffer[1024];
        ssize_t n = recv(sockfd, buffer, sizeof(buffer) - 1, 0); // 这里读取就不会阻塞了，因为已经有读事件就绪才进来的
        if (n > 0)
        {
            buffer[n] = '\0';
            std::cout << "client say@ " << buffer << std::endl;
        }
        else if (n == 0) // 读到0表示读到文件结尾，说明客户端退出了
        {
            CloseError(sockfd);
        }
        else
        {
            CloseClientQuit(sockfd);
        }
    }

   void CloseError(int sockfd)
   {
       LOG(LogLevel::INFO) << "recv error !";
       // 从epoll中移除fd的关心 && 关闭fd -- 细节：epoll_ctl: 只能移除合法fd -- 先移除，在关闭！！
       int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);
       if (m > 0)
       {
           LOG(LogLevel::INFO) << "epoll_ctl remove sockfd success: " << sockfd;
       }
       close(sockfd);
   }

   void CloseClientQuit(int sockfd)
   {
       LOG(LogLevel::INFO) << "clien quit...";
       // 从epoll中移除fd的关心 && 关闭fd -- 细节：epoll_ctl: 只能移除合法fd -- 先移除，在关闭！！
       int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);
       if (m > 0)
       {
           LOG(LogLevel::INFO) << "epoll_ctl remove sockfd success: " << sockfd;
       }
       close(sockfd);
   }


    void Stop()
    {
        _isrunning = false;
    }

    ~EpollServer() 
    {
        _listensock->Close();
        if(_epfd > 0)
            close(_epfd);
    }

private:
    std::unique_ptr<Socket> _listensock;
    bool _isrunning;
    int _epfd;
    struct epoll_event _revs[size]; //存放就绪事件的数组

    //struct pollfd _fds[size]; //设置为固定大小的数组，也可以设置为指针方便realloc扩容
    //int _fd_arry[size]; // 辅助数组,保存服务器历史获取过的所有的fd
};